/*
 *  Class name: GoalManagedBean.java
 *  Version: 1.0
 *  Date: 5.3.2014
 */
package cz.muni.fi.pa165.soccergamesarchive.managedbeans.entity;

import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.GoalDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.PlayerDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.services.PlayerServiceBeanLocal;
import cz.muni.fi.pa165.soccergamesarchive.datamodels.entity.PlayerDataModel;
import cz.muni.fi.pa165.soccergamesarchive.managedbeans.application.DialogChooserListenable;
import cz.muni.fi.pa165.soccergamesarchive.structures.RestrictionOperator;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.Dependent;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import static java.lang.Integer.parseInt;
import static javax.faces.context.FacesContext.getCurrentInstance;

/**
 *
 * @author Michal Ďuriš
 */
@Named(value = "goalManagedBean")
@Dependent
public class GoalManagedBean implements Serializable, DialogChooserListenable {

    private static final long serialVersionUID = 1L;

    @Inject
    private MatchManagedBean matchManagedBean;

    @EJB
    private PlayerServiceBeanLocal playerService;

    private PlayerDataModel playerDataModel;

    /**
     * Creates a new instance of GoalManagedBean
     */
    public GoalManagedBean() {
    }

    @PostConstruct
    public void init() {
        playerDataModel = new PlayerDataModel(playerService);

        playerDataModel.getFilterMap().put("lastName", "");
        playerDataModel.getFilterMap().put("homeTeam", null);
        playerDataModel.getFilterMap().put("awayTeam", null);

        playerDataModel.getFilterRestrictionOperatorsMap().put("lastName",
                RestrictionOperator.AND);
        playerDataModel.getFilterRestrictionOperatorsMap().put("homeTeam",
                RestrictionOperator.OR);
        playerDataModel.getFilterRestrictionOperatorsMap().put("awayTeam",
                RestrictionOperator.OR);
    }

    public void addGoal() {

        GoalDTO goal = new GoalDTO();
        goal.setSoccerMatch(matchManagedBean.getCurrentlyManagedMatch());

        matchManagedBean.getCurrentlyManagedMatch().getGoals()
                .add(goal);
    }

    public void removeGoal(int index) {

        matchManagedBean.getCurrentlyManagedMatch().getGoals().remove(index);
    }

    public void updateGoalList() {

        List<GoalDTO> goalList = matchManagedBean.getCurrentlyManagedMatch()
                .getGoals();

        if (goalList == null) {
            return;
        }

        for (Iterator<GoalDTO> it = goalList.iterator(); it.hasNext();) {
            GoalDTO goal = it.next();
            
            if(goal.getPlayer() == null) {
                continue;
            }

            if (!Objects.equals(matchManagedBean.getCurrentlyManagedMatch()
                    .getHomeTeam(), goal.getPlayer().getTeam())
                    && !Objects.equals(matchManagedBean
                            .getCurrentlyManagedMatch().getAwayTeam(), goal
                            .getPlayer().getTeam())) {
                it.remove();
            }
        }
    }

    public boolean validateGoals(FacesMessage errorMessage) {

        if (matchManagedBean.getCurrentlyManagedMatch().getGoals() != null
                && !matchManagedBean.getCurrentlyManagedMatch().getGoals()
                .isEmpty()) {

            FacesContext facesContext = getCurrentInstance();

            List<GoalDTO> goals = matchManagedBean.getCurrentlyManagedMatch()
                    .getGoals();

            boolean errorFlag = false;

            for (int i = 0; i < goals.size(); i++) {
                GoalDTO goal = goals.get(i);

                if (goal.getPlayer() == null) {
                    errorFlag = true;
                    facesContext.addMessage(
                            "matchEditorForm:goalsPanelRepeater:" + i
                            + ":goalScorer",
                            errorMessage);
                }
            }

            return !errorFlag;
        }

        return true;
    }

    @Override
    public Object getDataModel() {
        return playerDataModel;
    }

    @Override
    public Map<String, Object> getFilterMap() {
        return playerDataModel.getFilterMap();
    }

    @Override
    public void storeResult(String resultName, Object result) {

        if (result != null && result instanceof PlayerDTO) {

            if (resultName != null && !resultName.isEmpty()) {

                PlayerDTO scorer = (PlayerDTO) result;
                GoalDTO goal;

                try {
                    int index = parseInt(resultName.split("player")[1]);

                    goal = matchManagedBean.getCurrentlyManagedMatch()
                            .getGoals().get(index);

                    goal.setPlayer(scorer);

                } catch (NumberFormatException | IndexOutOfBoundsException ex) {
                    System.err.println(
                            "Class " + getClass().getName() + " throws: "
                            + ex);
                }
            }
        }

        playerDataModel.getFilterMap().put("lastName", "");
    }

}
